const express = require('express');
const bodyParse = require('body-parser');
var jwt = require('jsonwebtoken');
const app = express();
let secret = 'zxw';
app.use(function (req, res, next) {
    res.header('Access-Control-Allow-Origin', 'http://localhost:8081');
    //允许的header类型
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
    res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
    if (req.method.toLowerCase() == 'options')
        res.send(200);  //让options尝试请求快速结束
    else
        next();
});
app.use(bodyParse.json());
app.get('/user', (req, res) => {
    res.json({
        name: 'hello'
    })
})
app.post('/singup', async (req, res, next) => {
    let user = req.body;
    user = await user.create(user);
    if (user) {
        res.json({
            code: 0,
            data: {
                user
            }
        })
    } else {
        res.json({
            code: 1,
            data: '用户注册失败'
        });
    }
});
app.post('/login', (req, res, next) => {
    let { username } = req.body;
    if (username == 'admin') {
        res.json({
            code: 0,
            username: 'admin',
            token: jwt.sign({
                username: 'admin'
            }, secret, {
                expiresIn: 20
            })
        })
    } else {
        res.json({
            code: 1,
            data: '用户不存在'
        });
    }
})

app.get('/validate', (req, res) => {
    let token = req.headers.authorization;
    jwt.verify(token, secret, (err, decode) => {
        if (err) {
            return res.json({
                code: 1,
                data: 'token失效'
            })
        } else {
            return res.json({
                code: 0,
                username: decode.username,
                token: jwt.sign({
                    username: 'admin'
                }, secret, {
                    expiresIn: 20
                })
                //需要把token 的失效延长
            })
        }
    });
})
app.listen(3000);